package com.tedu.charging.service.bill.job;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tedu.charging.common.core.utils.DateUtils;
import com.tedu.charging.service.bill.dao.BillSuccesMapper;
import com.tedu.charging.service.bill.pojo.po.ChargingBillSucces;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;


import java.util.Date;
import java.util.UUID;

@Slf4j
public class ExceptionBillHandleJob implements Job {
    //保存开始充电的订单
    private static BillSuccesMapper billSuccesMapper;

    public static void setBillSuccesMapper(BillSuccesMapper mapper) {
        if (billSuccesMapper == null) {
            billSuccesMapper = mapper;
        }
    }

    //必须有无参构造方法
    public ExceptionBillHandleJob() {
    }

    public ExceptionBillHandleJob(String billId) throws Throwable {
        log.debug("添加定时任务：" + DateUtils.getTime());


        // 创建调度器工厂
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        // 创建定时任务
        JobDetail jobDetail = JobBuilder.newJob(ExceptionBillHandleJob.class)
                .withIdentity("ExceptionBillHandleJob" + UUID.randomUUID(), "group")
                .usingJobData("billId", billId)
                .build();

        // 创建触发器，设置触发时间
        Date triggerTime = new Date(System.currentTimeMillis() + 3 * 60 * 1000);  // 当前时间3分钟后
        Trigger trigger = TriggerBuilder.newTrigger()
                .startAt(triggerTime)
                .build();

        // 将定时任务和触发器绑定到调度器中
        scheduler.scheduleJob(jobDetail, trigger);

        // 启动调度器
        scheduler.start();
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("execute()" + DateUtils.getTime());
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String billId = jobDataMap.get("billId").toString();
        log.debug("billId=" + billId);

        //将订单改成异常订单
        ChargingBillSucces chargingBillSucces = new ChargingBillSucces();
        chargingBillSucces.setBillStatus(3);

        //查询开始充电中，没有正常结束的订单
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("bill_id", billId);

        //1:开始充电，正常订单开始充电后，充满后改成正常结束2
        updateWrapper.eq("bill_status", 1);
        billSuccesMapper.update(chargingBillSucces, updateWrapper);

    }
}
